package com.DHT;


import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class DHT {

    // key:服务器节点的位置，value:正式服务器
    private TreeMap<Long , ServerNode> dht = new TreeMap<>();



    public void ListData() {
        for (Map.Entry<Long, ServerNode> e : dht.entrySet()) {
            System.out.println(e.getValue().getIp());
            e.getValue().ListData();
        }
    }


    //像哈希环中添加一个节点
    public void addNode(ServerNode node) {
        long hashValue = Math.abs(node.getIp().hashCode());
        long key =  hashValue % 4294967296L;

        System.out.println("节点位置" + key);
        dht.put(key,node);
    }


    //添加实际数据
    public void addData(String Key) {
        long key = Math.abs(Key.hashCode());
        long pos =  key % 4294967296L;
        System.out.println("数据真实位置:" + pos);
        //对Key取余后，沿顺时针下找到第一个节点
        SortedMap<Long, ServerNode> map = dht.tailMap(pos);
        Long serverKey;

        if(map.size() == 0) {
             serverKey = dht.firstKey();
        }
        else {
             serverKey = map.firstKey();
        }

        ServerNode serverNode = dht.get(serverKey);
        serverNode.addData(Key);


    }
}
